package smecta.client.print.util;

import smecta.client.print.common.exceptions.ServiceException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class MachineCodeUtil {

    // 生成的机器码
    public static String generateMachineCode() {
        try {
            return getMacAddress() + "-" + getHardDriveSerialNumber();
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }


    // 获取MAC地址
    private static String getMacAddress() throws Exception {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();
            byte[] mac = ni.getHardwareAddress();
            if (mac != null) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    sb.append(String.format("%02X", mac[i]));
                }
                return sb.toString();
            }
        }
        throw new Exception("MAC address not found");
    }

    // 获取硬盘序列号
    private static String getHardDriveSerialNumber() throws Exception {
        Process process = Runtime.getRuntime().exec("wmic diskdrive get serialnumber");
        process.getOutputStream().close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        boolean foundHeader = false;
        String serialNumber = "";
        int number = 0;
        String firstLine = "";
        String secondLine = "";
        while ((line = reader.readLine()) != null) {
            if (number == 0) {
                firstLine = line.trim();
            } else if (number == 1) {
                secondLine = line.trim();
            }
            if (foundHeader) {
                serialNumber = line.trim();
                break;
            }
            if (line.trim().equalsIgnoreCase("SerialNumber")) {
                foundHeader = true;
            }
            number++;
        }

        if (serialNumber.isEmpty()) {
            if (!secondLine.isEmpty())
                serialNumber = secondLine;
            else
                serialNumber = firstLine;
        }

        reader.close();
        return serialNumber;
    }
}
